package com.gjy.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-10 14:16:45
 */
public class StringReplayDecoder extends ReplayingDecoder<StringReplayDecoder.Phase> {

    private static final Logger logger = LoggerFactory.getLogger(StringReplayDecoder.class);
    private int length;
    private byte[] content;

    public StringReplayDecoder() {
        super(Phase.PHASE_1);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        switch (state()) {
            case PHASE_1:
                length = in.readInt();
                content = new byte[length];
                checkpoint(Phase.PHASE_2);
                break;
            case PHASE_2:
                in.readBytes(content, 0, length);
                out.add(new String(content, CharsetUtil.UTF_8));
                checkpoint(Phase.PHASE_1);
                break;
            default:
                break;
        }
    }

    enum Phase {
        PHASE_1, PHASE_2
    }
}
